﻿using Autofac.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using SH.Common;
using SH.Common.CommonReturn;
using SH.Common.DataDictionary;
using SH.Multitenant.API.Filters;
using SH.Multitenant.Application.IServices.IDic;
using SH.Multitenant.Domain.Multitenant;
using SH.Multitenant.Infrastructure.Repository;
using SqlSugar;


namespace SH.Multitenant.API.Controllers
{
    /// <summary>
    /// 数据字典控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DicController : ControllerBase
    {
        private readonly IDicServices _dicServices;

        public DicController(IDicServices dicServices)
        {
            _dicServices = dicServices;
            
        }
        /// <summary>
        /// 数据字典增加
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        [HttpPost]
        [LogActionFilter("Dic", "数据字典增加")]
        public async Task<IActionResult> DicAddAsync(Dic dic)
        {
            
            var result = await _dicServices.DicAddAsync(dic);
            ApiResult<int> apiResult = new ApiResult<int>();
            apiResult.Success(result);
            return Ok(apiResult);
        }
        /// <summary>
        /// 数据字典删除
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        [HttpPost]
        [LogActionFilter("Dic", "数据字典删除")]
        public async Task<IActionResult> DicDeleteAsync(Dic dic)
        {
            var result = await _dicServices.DicDeleteAsync(dic);
            ApiResult<int> apiResult = new ApiResult<int>();
            apiResult.Success(result);
            return Ok(apiResult);
        }
        /// <summary>
        /// 数据字典修改
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        [HttpPost]
        [LogActionFilter("Dic", "数据字典修改")]
        public async Task<IActionResult> DicUpdAsync(Dic dic)
        {
            var result = await _dicServices.DicUpdAsync(dic);
            ApiResult<int> apiResult = new ApiResult<int>();
            apiResult.Success(result);
            return Ok(apiResult);
        }
        /// <summary>
        /// 数据字典批量删除
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [HttpPost]
        [LogActionFilter("Dic", "数据字典批量删除")]
        public async Task<IActionResult> BatchDicsDelAsync(List<Dic> list)
        {
            var result = await _dicServices.BatchDicsDelAsync(list);
            ApiResult<int> apiResult = new ApiResult<int>();
            apiResult.Success(result);
            return Ok(apiResult);
        }
        /// <summary>
        /// 批量导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [LogActionFilter("Dic", "数据字典批量导入")]
        public async Task<IActionResult> BatchImportDics(IFormFile file)
        {
            //var file = Request.Form.Files[0];//要处理文件
            //获取文件名
            var fileName = file.FileName;
            //获取后缀名
            var fileExtension = Path.GetExtension(fileName);
            //判断后缀名是否为xlsx或xls
            if (fileExtension != ".xlsx" && fileExtension != ".xls")
            {
                return BadRequest("文件格式不正确");
            }
            var fileSize = file.Length;
            if (fileSize > 1024 * 1024 * 10)
            {
                return BadRequest("文件大小不能超过10M");
            }
            IEnumerable<Dic> list = new List<Dic>();
            //MemoryStream内存流 在内存中开辟一个空间
            using (var stream = new MemoryStream())
            {
                file.CopyTo(stream);
                //将流的位置归零
                stream.Position = 0;
                //将内存流转成集合
                list = await stream.QueryAsync<Dic>();
                //Queues the specified work to run on the thread pool and returns a proxy for the task returned by function
                await Task.Run(async () =>
                {
                    await _dicServices.DicBatchInsertAsync(list.ToList());
                });
            }
            //Task.Run(x => { await _services.InsertBatchAsync(list)});
            //var rows = MiniExcel.Query<User>(path);
            return Ok(fileName);
        }
        /// <summary>
        /// 分页获取字典列表
        /// </summary>
        /// <param name="module"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> PagingDicsListAsync(string? identification, int pageSize, int pageIndex)
        {
            var result = await _dicServices.PagingDicsListAsync(identification, pageSize, pageIndex);
            return Ok(result);
        }
        /// <summary>
        /// 根据唯一标识获取字典实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetDicByIdAsync(int id)
        {
            var result = await _dicServices.GetDicByIdAsync(id);
            ApiResult<Dic> apiResult = new ApiResult<Dic>();
            apiResult.Success(result);
            return Ok(apiResult);
        }
        //[HttpPost("export")]
        //public async Task<IActionResult> ExportExcel()
        //{
        //    var userList = _dicServices.All.ToList();
        //    var memoryStream = new MemoryStream();
        //    await memoryStream.SaveAsAsync(userList);
        //    memoryStream.Seek(0, SeekOrigin.Begin);
        //    return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        //    {
        //        FileDownloadName = "字典数据导出.xlsx"
        //    };
        //    //MiniExcel.SaveAs(path, userList);
        //}

        /// <summary>
        /// 根据标识列获取字典列表
        /// </summary>
        /// <param name="identification"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetDicByIdentification(string identification)
        {
            ApiResult<List<Dic>> apiResult = new ApiResult<List<Dic>>();
            var list = await _dicServices.GetDicByIdentificationAsync(identification);
            apiResult.Success(list);
            return Ok(apiResult);
        }

        /// <summary>
        /// 获取省市级联列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCascaderList()
        {
            var result = _dicServices.GetCascaderList();
            ApiResult<List<Cascader>> apiResult = new ApiResult<List<Cascader>>();
            apiResult.Success(result);
            return Ok(result);
        }
    }
}
